package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.exception.LogicException;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.query.QueryObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;


    // 添加员工信息
    @Override
    public void save(Employee employee, Long[] ids) {
        employeeMapper.insert(employee);
        // 添加一条员工信息后,再往中间表插入 关联角色的 roleId 值
        saveRelation(employee, ids);
    }

    // 中间表插入关联信息
    private void saveRelation(Employee employee, Long[] ids) {
        if (ids != null && ids.length > 0) {
            // 重新往中间表添加数据(新分配的角色数据)
            for (Long employeeId : ids) {
                employeeMapper.insertRelation(employee.getId(), employeeId);
            }
        }
    }

    // 删除
    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
        employeeMapper.deleteRelation(id);
    }

    // 修改
    @Override
    public void update(Employee employee, Long[] ids) {
        // 如果 id 不为0,先删除原有的 employee 的 ID ,再重新添加
        // 修改员工信息
        employeeMapper.updateByPrimaryKey(employee);
        // 往中间表 employee_role 删除与该 员工 相关的数据
        employeeMapper.deleteRelation(employee.getId());
        saveRelation(employee, ids);

    }



    // 根据 id 查询信息
    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    // 查询所有信息
    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    // 分页查询信息
    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        return new PageInfo<>(employeeMapper.selectForList(qo));
    }

    // 查询用户名和密码
    @Override
    public Employee login(String username, String password) {
        if (!StringUtils.hasText(username)){
            throw new LogicException("用户名不能为空");
        }
        Employee employee = employeeMapper.selectByUsernameAndpassword(username, password);
        if (employee == null){ // 没有查询到
            throw new LogicException("账号或密码不正确");
        }
        return employee;
    }

    // 批量删除
    @Override
    public void deleteALL(Long[] ids) {
        employeeMapper.deleteAll(ids);
    }

    // 查询用户名
    @Override
    public Employee selectByName(String name) {
        Employee employee = employeeMapper.selectByName(name);
        return employee;
    }

    // 导出文件
    @Override
    public Workbook exportXls(){
        // 创建工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建工作表
        HSSFSheet sheet = workbook.createSheet("用户信息表");
        // 创建行,列
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("用户名");
        row.createCell(1).setCellValue("密码");
        row.createCell(2).setCellValue("年龄");
        // 遍历读取所有用户信息
        List<Employee> employees = employeeMapper.selectAll();
        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);
            // 有多少个用户创多少行,索引为 i+1,已经存在第一行
            row = sheet.createRow(i+1);
            System.out.println(row);
            // 每个用户一行,创3个单元格
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getPassword());
            row.createCell(2).setCellValue(employee.getAge());
        }
        return workbook;
    }

    // 导入文件
    @Override
    public void importXls(Part file) throws Exception {
        // 接收一个 file ,转成 Workbook 对象
        Workbook workbook = new HSSFWorkbook(file.getInputStream());
        // 读取第一页
        Sheet sheet = workbook.getSheetAt(0);
        // 获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        // 从索引为 1 开始读
        for (int i = 1; i <= lastRowNum; i++) {
            // 从第二行开始读
            Row row = sheet.getRow(i);
            //判断如果用户名是空，就不再往下读
            String name = row.getCell(0).getStringCellValue();
            if(!StringUtils.hasLength(name.trim())){
                return;
            }
            // 获取单元格内容
            Employee employee = new Employee();
            employee.setName(name);
            employee.setPassword(row.getCell(1).getStringCellValue());
            CellType cellType = row.getCell(2).getCellType();
            if (cellType == CellType.STRING){
                employee.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));
            }else {
                employee.setAge((int)row.getCell(2).getNumericCellValue());
            }
            // 调用添加方法
            employeeMapper.insert(employee);
        }
    }

    // 验证用户名
    @Override
    public Map<String,Boolean> checkByName(String name, Long id) {
        HashMap<String, Boolean> map = new HashMap<>();
        // 如果 id 不为空,并且 传入的 name 和 数据库中根据 id 查询出来的 name 相等
        // 则通过验证,否则需要调用验证方法 , 判断 用户名 是否存在
        if (id!=null && name.equals(employeeMapper.selectById(id).getName())){
            // true 表示验证通过
            map.put("valid",true);
        }else {
            // 如果查询的用户为空,则表示验证通过
            Employee employee = employeeMapper.selectByName(name);
            map.put("valid",employee == null);
        }
        return map;
    }

    // 修改密码
    @Override
    public void updatePwd(Long id,String newPassword) {
        employeeMapper.updatePwd(id,newPassword);
    }

    // 查询密码
    @Override
    public Employee selectPassword(Long id) {
        Employee employee = employeeMapper.selectById(id);
        return employee;
    }

    // 修改用户状态
    @Override
    public void updateStatus(Long id,boolean status) {
        employeeMapper.updateStatus(id,status);
    }

    @Override
    public List<Employee> selectSellers(String[] roleName) {
        return employeeMapper.selectSellers(roleName);
    }

    @Override
    public List<Employee> selectName() {
        return employeeMapper.selectName();

    }
}
